package ms.unicorn.diagram.figures;

import ms.unicorn.dsl.IFigureEx;
import ms.unicorn.dsl.ITheme;
import ms.unicorn.dsl.impl.Theme;
import ms.unicorn.dsl.utils.ExceptionUtil;

import org.eclipse.draw2d.ConnectionAnchor;
import org.eclipse.draw2d.ConnectionLocator;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.RotatableDecoration;
import org.eclipse.draw2d.geometry.PrecisionPoint;
import org.eclipse.gmf.runtime.draw2d.ui.figures.PolylineConnectionEx;

public class ConnectionFigure extends PolylineConnectionEx implements IFigureEx {
	private String name;
	private int flag;
	private ITheme theme;

	public ConnectionFigure(String name) {
		this.name = name;
	}
	
	@Override
	protected ConnectionAnchor createAnchor(PrecisionPoint p) {
		return super.createAnchor(p);
	}
	
	@Override
	protected ConnectionAnchor createDefaultAnchor() {
		return super.createDefaultAnchor();
	}
		
	@Override
	protected void outlineShape(Graphics g) {
		ITheme theme = getTheme();
		g.setForegroundColor(theme.getForeColor());
		g.setLineWidthFloat(theme.getLineWidth());
		g.setLineStyle(theme.getLineStyle());
		setSmoothness(theme.getLineSmoothness());
		setRoundedBendpointsRadius(theme.getRoundedBendpointsRadius());
		// update the decorator if necessary
		Class<RotatableDecoration> decorClass = theme.getTargetDecorator();
		Class<ConnectionLocator> locatorClass = theme.getTargetDecorationLocator();
		try {
			if (decorClass != null && !decorClass.isInstance(getTargetDecoration())) {
				if (locatorClass != null)
					setTargetDecoration(decorClass.newInstance(), locatorClass.newInstance());
				else setTargetDecoration(decorClass.newInstance());
			}
			decorClass = theme.getSourceDecorator();
			locatorClass = theme.getSourceDecorationLocator();
			if (decorClass != null && !decorClass.isInstance(getSourceDecoration())) {
				if (locatorClass != null)
					setSourceDecoration(decorClass.newInstance(), locatorClass.newInstance());
				else setSourceDecoration(decorClass.newInstance());
			}	
		}
		catch(Exception ex) {
			ExceptionUtil.handleException(ex);
		}
		super.outlineShape(g);
	}

	@Override
	public String getName() {
		return this.name;
	}

	@Override
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public int getFlag() {
		return this.flag;
	}

	@Override
	public void setFlag(int flag) {
		this.flag = flag;
	}

	@Override
	public ITheme getTheme() {
		return this.theme != null ? theme : Theme.DEFAULT;
	}

	@Override
	public void setTheme(ITheme theme) {
		this.theme = theme;
	}
}
